package com.example.hms.service.servicelmpl;

import com.example.hms.dao.UserDao;
import com.example.hms.entity.User;
import com.example.hms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utll.Result;
import utll.ResultSubmit;
import utll.TokenUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class UserServicelmpl implements UserService {
    @Resource
//    @Autowired
    private UserDao userDao;

    @Override
    public Result login(String userId, String password, HttpServletRequest request){
        User user = userDao.login(userId);
        if(user == null){
            return ResultSubmit.error("登录失败，账户不存在");
        }
        if (password.equals(user.getUserPassword())){

            HttpSession session = request.getSession();
            session.setAttribute("userId", user.getUserId());
            session.setAttribute("userName", user.getUserName());
            session.setAttribute("roleName", user.getRoleName());
            Long time = System.currentTimeMillis();
            session.setAttribute("time", time);
            session.setAttribute("token", TokenUtil.getToken(
                    String.valueOf(user.getUserId()),user.getRoleName(),time));

            return ResultSubmit.success(sweet(user));
        }else {
            return ResultSubmit.error("登录失败，密码错误");
        }

    }

    private User sweet(User user){
        User sweet = new User();
        sweet.setUserId(user.getUserId());
        sweet.setUserName(user.getUserName());
        sweet.setRoleName(user.getRoleName());
        return sweet;
    }

}
